package com.test.ayi.test.competablefuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CFtest6AllOf {
    public static void main(String[] args) throws InterruptedException {
        // 创建线程池
        ExecutorService executor = Executors.newFixedThreadPool(3);

        // === 定义 3 个并行的 CompletableFuture 任务 ===
        CompletableFuture<String> task1 = CompletableFuture.supplyAsync(() -> {
            sleep(1000);
            return "Hello";
        }, executor);

        CompletableFuture<Integer> task2 = CompletableFuture.supplyAsync(() -> {
            sleep(800);
            return 2025;
        }, executor);

        CompletableFuture<String> task3 = CompletableFuture.supplyAsync(() -> {
            sleep(2200);
            //int i = 1/0;
            return "World";
        }, executor);

        // === 核心：使用 allOf + thenApply 实现优雅合并 ===
        CompletableFuture
                .allOf(task1, task2, task3)                    // 等待全部完成
                .thenApply(v -> {                              // v 是 Void（占位）
                    // 使用 join() 安全获取结果（不会抛受检异常）
                    return task1.join() + " " + task2.join() + " " + task3.join();
                })
                .exceptionally(ex -> ex.getMessage())                         // 异常处理)
                .thenAccept(result -> {
                    System.out.println("合并结果: " + result);
                    // 输出: 合并结果: Hello 2025 World
                });
        System.out.println("hello,world,☺️");

        // 关闭线程池
        executor.shutdown();
    }

    private static void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}
